package com.cy.store.controller;


import com.cy.store.entity.Product;
import com.cy.store.service.ICartService;
import com.cy.store.service.IProductService;
import com.cy.store.util.JsonResult;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("carts")
public class CartController extends BaseController{

    @Autowired
    private ICartService cartService;

    @RequestMapping("add_to_cart")
    public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行添加到购物车
        cartService.addToCart(uid, pid, amount, username);
        // 返回成功
        return new JsonResult<>(OK);
    }

    @RequestMapping({"", "/"})
    public JsonResult<List<CartVO>> getVOByUid(HttpSession session) {
    // 从Session中获取uid
        Integer uid = getuidFromSession(session);
    // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByUid(uid);
    // 返回成功与数据
        return new JsonResult<>(OK, data);
    }

//采用restful方法进行前后端交互，得有@PathVariable
    @RequestMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession session) {
        // 调用业务对象执行增加数量
        Integer data = cartService.addNum(cid, getuidFromSession(session), getUsernameFromSession(session));
        // 返回成功
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("{cid}/num/delete")
    public JsonResult<Integer> deleteNum(@PathVariable("cid") Integer cid, HttpSession session) {
        // 调用业务对象执行增加数量
        Integer data = cartService.deleteNum(cid, getuidFromSession(session), getUsernameFromSession(session));
        // 返回成功
        return new JsonResult<>(OK, data);
    }


    /**
     * 传递cids的数组 {1，2，3，4}  cids=1&cids=2&cids=3.....
     * @param cids
     * @param session
     * @return
     */
    @RequestMapping("list")
    public JsonResult<List<CartVO>> getVOByCids(Integer[] cids, HttpSession session)
    {
    // 从Session中获取uid
        Integer uid = getuidFromSession(session);
    // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByCids(uid, cids);
    // 返回成功与数据
        return new JsonResult<>(OK, data);
    }









}
